<template>
	<!-- <el-card>
		<el-form ref="queryForm" :inline="true">
			<el-form-item prop="postCode" label="关键词:">
				<el-input v-model="queryParams.keywords" placeholder="关键词"></el-input>
			</el-form-item>

			<el-form-item>
				<el-button icon="Search" type="primary" @click="handleSearch">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button icon="RefreshRight" @click="handleReset">重置</el-button>
			</el-form-item>
		</el-form>
	</el-card> -->

	<el-form :inline="true" style="text-align: right">
		<el-form-item>
			<el-button type="primary" @click="addOrUpdateHandle(true, {})">新增</el-button>
		</el-form-item>
	</el-form>
	<el-card>
		<el-table
			v-loading="loading"
			:data="dataList"
			class="mt15"
			stripe
			element-loading-background="rgba(0, 0, 0, 0.5)"
			element-loading-text="加载中..."
			header-row-class-name="table-header"
		>
			<el-table-column type="index" label="序号" header-align="center" align="center" width="60"></el-table-column>
			<el-table-column label="模板名称" align="center" prop="filename" />

			<el-table-column label="上传时间" align="center" prop="uploadTime"> </el-table-column>
			<el-table-column label="上传人" align="center" prop="reportPerson"> </el-table-column>
			<el-table-column label="项目类型" align="center" prop="templateTypeValue"> </el-table-column>
			<el-table-column label="状态" align="center" prop="status"> </el-table-column>

			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="120">
				<template #default="scope">
					<el-icon :size="16" color="#1491FF" title="编辑" style="cursor: pointer; margin: 0 6px" @click="addOrUpdateHandle(false, scope.row, 1)">
						<Edit />
					</el-icon>
					<el-icon :size="16" color="#fe6360" title="删除" style="cursor: pointer; margin: 0 6px" @click="deleteBatchHandle(scope.row.id)">
						<Delete />
					</el-icon>

					<el-icon :size="16" color="#1491FF" title="模板下载" style="cursor: pointer; margin: 0 6px" @click="downBatchHandle(scope.row)"
						><Download
					/></el-icon>
				</template>
			</el-table-column>
		</el-table>

		<el-pagination
			:current-page="pageInfo.pageIndex"
			:page-size="pageInfo.pageSize"
			:total="pageInfo.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
		>
		</el-pagination>

		<AddDialog ref="addOrUpdateRef" @refresh-data-list="getDataList" />
	</el-card>
</template>
<script setup lang="ts">
import { deleteApi, templateFilelistApi } from '@/api/system/Templatefile'
import { useUserStore } from '@/store/modules/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, ref } from 'vue'
import AddDialog from './components/addDialog.vue'

const userStore = useUserStore()
// import { Download } from '@element-plus/icons-vue/dist/types'
const queryParams = ref({ keywords: '', date: '', dept_id: '' })
const queryForm = ref()

const dataList = ref([])
const loading = ref(false)
const pageInfo = ref({ pageIndex: 1, pageSize: 10, total: 0 })
onMounted(() => {
	getDataList()
})

const getDataList = () => {
	loading.value = true
	const data = { pageIndex: pageInfo.value.pageIndex, pageSize: pageInfo.value.pageSize }
	templateFilelistApi(data).then(res => {
		loading.value = false
		dataList.value = res.data.list || []
		pageInfo.value.total = res.data.total || 0
	})
}

const handleSizeChange = (val: number) => {
	pageInfo.value.pageSize = val
	dataList.value = []
	getDataList()
}
const handleCurrentChange = (val: number) => {
	pageInfo.value.pageIndex = val
	dataList.value = []
	getDataList()
}

const deleteBatchHandle = (id: String | Number) => {
	ElMessageBox.confirm('是否删除?', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			delMethods(id)
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '删除失败'
			})
		})
}

const delMethods = async (id: String | Number) => {
	await deleteApi({ id: id }).then(res => {
		ElMessage.success('删除成功')
		reset()
	})
}
async function downloadFile(url, row: any) {
	try {
		// 发起请求
		const response = await fetch(url, {
			method: 'GET',
			headers: {
				Authorization: userStore.token, // 在 Header 中传递 token
				'Content-Type': 'application/json' // 根据实际需求设置 Content-Type
			}
		})

		if (!response.ok) {
			throw new Error(`下载失败: ${response.statusText}`)
		}

		// 获取文件数据
		const blob = await response.blob()

		// 创建下载链接
		const downloadLink = document.createElement('a')
		downloadLink.href = URL.createObjectURL(blob)
		downloadLink.download = row.filename // 设置下载文件名(根据实际需求修改)
		document.body.appendChild(downloadLink)
		downloadLink.click()
		document.body.removeChild(downloadLink)
	} catch (error) {
		console.error('下载过程中出错:', error)
	}
}

const downBatchHandle = async (row: any) => {
	const url = window.location.protocol + '//' + window.location.host + '/JGBStandardWebApi' + `/api/files/${row.file.id}/downloadByFileId`
	await downloadFile(url, row)
}
const reset = () => {
	pageInfo.value.pageSize = 10
	pageInfo.value.pageIndex = 1
	dataList.value = []
	pageInfo.value.total = 0
	getDataList()
}

// 新增编辑
const addOrUpdateRef = ref()
const addOrUpdateHandle = (isUpdate: Boolean, row: any) => {
	addOrUpdateRef.value.init(isUpdate, row)
}
</script>

<style lang="scss" scoped></style>
